import { clearUrlHttp, drawCardToBase64, DrawCardToBase64Option, handleImageUrlToWebp, replaceHtmlToSafeStr, timestampToDate } from '../../utils'
import Card, { CardValue, LOAD_STATUS } from '../card'

export interface MallCardInfo {
    city_name: string,
    district_name: string,
    end_time: number,
    id: number,//商品id
    name: string,//商品名称
    performance_image: string,
    price_low: number,
    province_name: string,
    start_time: number,
    venue_name: string,
    url: string,//商品详情链接
}

export type MallCardCreateValue = CardValue<MallCardInfo>
export default class MallCard extends Card {
    static blotName = 'mall-card'
    static className = 'mall-card'

    static create(value: MallCardCreateValue) {
        // 根据id获取商品信息，将商品新增转为图片，最终插入图片，并将id作为data-id，存入的参数中
        const node: HTMLElement = super.create(value)
        if (value !== null && value?.status === LOAD_STATUS.LOADED) return node
        node.setAttribute('contenteditable', 'false')
        if (!value.src && !value.id) return node
        node.classList.add('card')
        const type = this.verify(value)
        return type === 'render' ? (this.renderHandle(value, node), node) :
            type === 'draw' ? (this.drawHandle(value, node), node) :
                node
    }

    static renderHandle(value: MallCardCreateValue, node: HTMLElement) {
        value.id && this.renderCard(value).then((dom: HTMLElement) => { node.appendChild(dom) })
    }
    static drawHandle(value: MallCardCreateValue, node: HTMLElement) {
        // return node
        const { id } = value
        if (id) {
            const loadingImage = this.createLoadingImage()
            node.appendChild(loadingImage)
            return this.drawCard(id, value).then((res) => {
                value.src = res
                value?.uploadHandle?.(loadingImage, value) || this.uploadHandle?.(loadingImage, value)
                return null
            })
        }
    }
    static renderCard(value: MallCardCreateValue) {
        const { id, info } = value
        return id && info ? createMallCardDom(info).then((res) => {
            return res.dom
        }) : getMallDetail(id).then((res) => {
            return createMallCardDom(res[id]).then((res) => {
                return res.dom
            })
        })
    }
    static drawCard(id: string, value: MallCardCreateValue) {
        const render = async (v: MallCardCreateValue['info']) => {
            const res = await createMallCardDom(v, { draw: true, wrap: document.querySelector(this.drawWrap) as HTMLElement })
            return res.base64!
        }
        return value.info ? render(value.info) : getMallDetail(id).then(res => {
            return render(res[id])
        })
    }
}

const createMallCardDom = (
    info: MallCardCreateValue['info'],
    option?: DrawCardToBase64Option
) => {
    let t: string | null | undefined
    const n: Record<string, any> = info || {}
    const r = option || {}
    const i = n.itemsId || n.id || undefined
    const e = n.img
    let o = ''
    if (!i) {
        o = ` <div class="read-error-card media mobile slim-border">
              <p class="p-1"></p>
                <p class="flex items-center justify-center p-2">
                  <i class="card-icon icon-warning mr-1"></i>
                  <span>商品加载失败</span>
                </p>
              <p class="p-3"></p>
            </div>`
        r.className = 'card-container mall-card'
    }
    const a = n.id && n.district_name //存在id 和 district_name
    const c = a ? `pw${i || ''}` : `sp${i || ''}`
    t = r.cvid
    const u = a
        ? n.url
        : `//mall.bilibili.com/detail.html?loadingShow=1${r.shopId ? '&shopId=' + r.shopId : ''
        }&noTitleBar=1&from=articleDetail&cvid=${t || '0'}&jumpLinkType=${n.jumpLinkType
        }#itemsId=${i}`

    const s = a ? n.price_low : n.price / 100 || '价格待定'
    const l = n.name
    const f = a
        ? `${timestampToDate(1000 * n.start_time, true)}-${timestampToDate(
            1000 * n.end_time,
            true
        )} ${n.venue_name}`
        : n.brief || l
    const p = a
        ? n.performance_image
        : (e === null || e === undefined ? undefined : e[0]) || ''

    o = `<a class="mall-card-holder normal-card" data-card-type="mall" data-card-id="${c}" href="${clearUrlHttp(
        u
    )}" target="_blank">
          <div class="flex pointer-events-none mall-card-ctnr">
            <div class="cover-box ${p ? 'show-img' : ''}">
              <i class="card-icon icon-cover default-cover"></i>
              <div class="cover-img" style="background-image:url(${handleImageUrlToWebp(
        clearUrlHttp(p),
        64 * devicePixelRatio,
        64 * devicePixelRatio,
        1,
        1
    )})"></div>
            </div>
            <div class="flex-1 min-w-0 flex flex-col justify-between mall-cnt-box">
              <div class="mall-info-box">
                <div class="truncate mall-name">${replaceHtmlToSafeStr(l)}</div>
                <div class="multiple-ellipsis mall-desc" style="-webkit-box-orient: vertical;">${replaceHtmlToSafeStr(
        f
    )}</div>
              </div>
              <div class="flex items-center mall-bottom-box">
                <div class="flex-1 min-w-0 flex items-baseline mall-price-box">
                  <span>¥</span>
                  <span class="price">${replaceHtmlToSafeStr(
        r.draw ? '--' : s + '起'
    )}</span>
                </div>
              </div>
            </div>
          </div>
        </a>`
    r.className = 'card-container mall-card'
    // 通过html2Canvas 生成图片后插入
    return drawCardToBase64(o, r)
}

export const getMallDetail = (itemId: string): Promise<Record<string, MallCardCreateValue['info']>> => {
    // 请求接口获取卡片信息
    return Promise.resolve({
        [itemId]: {
            city_name: '',
            district_name: '',
            end_time: 0,
            id: 11115712,
            name: 'bilibiliGoods 哔哩哔哩拜年纪 蛇舞昭华系列 桌垫 A款/B款',
            performance_image: '',
            price_low: 69,
            province_name: '',
            start_time: 0,
            url: 'https://mall.bilibili.com/detail.html?msource=column&loadingShow=1&noTitleBar=1#itemsId=11115712',
            venue_name: '',
        },
    })
}
